package com.yingxin.yxerp.module.dingtalk.util;

import com.yingxin.yx.framework.commons.constant.PathConst;
import com.yingxin.yx.framework.commons.enums.BusinessType;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yx.framework.commons.helper.PropertiesHelper;
import com.yingxin.yx.framework.commons.id.IdHelper;
import com.yingxin.yxerp.module.attachment.entity.Attachment;
import com.yingxin.yxerp.module.attachment.service.IAttachmentRelationService;
import com.yingxin.yxerp.module.attachment.service.IAttachmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Calendar;


/**
 * 企业微信 - 文件下载
 */

@Service
public class WeComFileDownloadUtil {

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private IAttachmentRelationService attachmentRelationService;

    public Attachment download(String requestUrl, String fileName, String bizId, String bizType) {
        try{
            URL url = new URL( requestUrl );
            HttpURLConnection connection = ( HttpURLConnection ) url.openConnection();
            // 设置请求方式 get
            connection.setRequestMethod( "GET" );
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("contentType", "utf-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            // 请求超时
            connection.setConnectTimeout( 5000 );
            int responseCode = connection.getResponseCode();

            // 获取文件信息
            String contentDisposition = connection.getHeaderField("Content-Disposition");
            // 解析contentDisposition中的文件名
            // 文件名称
            String filename = null;
            // 文件扩展名
            String extension = null;
            if (contentDisposition != null) {
                String[] parts = contentDisposition.split(";");
                for (String part : parts) {
                    if (part.trim().startsWith("filename")) {
                        filename = part.substring(part.indexOf('=') + 1).trim().replaceAll("\"", "");
                        try {
                            filename = URLDecoder.decode(filename, "UTF-8"); // 尝试使用UTF-8解码
                            extension = filename.substring(filename.lastIndexOf('.') + 1);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            // 文件大小
            long size = Long.valueOf( connection.getHeaderField("Content-Length") );

            if( responseCode == 200 ){
                InputStream inputStream = connection.getInputStream();
                BufferedInputStream bufferedInputStream = new BufferedInputStream( inputStream );
                String saveFileName = getSaveFileName( fileName + "." + extension );
                FileOutputStream outputStream = new FileOutputStream( saveFileName );

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.close();
                bufferedInputStream.close();
                inputStream.close();

                Attachment attachment = new Attachment();
                attachment.setId(IdHelper.snowflakeId());
                attachment.setFileName( fileName + "." + extension );
                attachment.setExt(extension);
                attachment.setPath( saveFileName.replaceAll("\\\\", "/") );
                attachment.setSize( size );
                attachmentService.save( attachment );
                if (StringUtils.isNotBlank(bizId)) {
                    // 解除之前的关联
                    attachmentRelationService.delete( bizId, BusinessType.getEnum( bizType ), null );
                    // 重新关联
                    attachmentRelationService.create( attachment.getId(), bizId, bizType, null );
                }
                return attachment;
            }
        }catch (Exception e){
            throw new BizException( e.getMessage() );
        }
        return null;
    }

    /**
     * 根据文件名获取完整的保存路径
     */
    private String getSaveFileName(String filename){
        String uploadDir = PropertiesHelper.getInstance().getProperty(PathConst.UPLOAD_DIR);
        //日期路径
        String dirPath = getPath(uploadDir);
        // 随机文件名
        // String randomName = UUID.randomUUID().toString().replace("-", "");
        String randomName = IdHelper.snowflakeId();
        //后缀
        String ext = getFileExt(filename);
        // uri
        String path = dirPath + randomName;
        if (StringUtils.isNotBlank(ext)) {
            path = path + "." + ext;
        }
        return uploadDir + path;
    }

    /**
     * getPath
     */
    private static String getPath(String uploadDir) {
        Calendar calendar = Calendar.getInstance();
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH) + 1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        // String path = File.separator + "wecom" + File.separator + year
        //         + File.separator + month + File.separator + day + File.separator;
        String path = File.separator + "wecom" + File.separator;
        File file = new File(uploadDir + path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }

    /**
     * get后缀
     */
    private static String getFileExt(String originalFilename) {
        int idx = originalFilename.lastIndexOf(".");
        if (idx > 0 && idx != (originalFilename.length() - 1)) {
            return originalFilename.substring(idx + 1);
        }
        return "";
    }

}
